package com.huluobo.a2210mdmdemo.myViews

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.LinearInterpolator
import kotlinx.coroutines.runBlocking

/**
 *  Created by LC on 2025/4/7.
 *  1个参的构造方法一般用于在代码中创建一个View 比如在页面上展示一个礼物布局
 *  2个参的构造方法一般用在xml中创建一个View,自带宽高属性,也就保存在第二个参数中
 *  3个参数和4个参数的不常用,第三个和第四个参数一般用于风格(Style)文件
 */
class MyView(context: Context) : View(context) {

    //测量 widthMeasureSpec 都包含一个mode一个size,前2位保存模式,后30位保存大小
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    //摆放 View之中摆放View的位置,一般单独的View不使用这个方法,ViewGroup中才会使用,View中没法放View
    //注意LTRB分别代表距离左侧和上侧的位置
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
    }

    private lateinit var paint: Paint
    private lateinit var paintText: Paint

    //绘制的角度
    private var progress = 0f
    private var num = 5

    init {
        initPaint()
        start()
    }

    private fun initPaint() {
        paint = Paint()
        paint.color = Color.RED
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 5f
        paintText = Paint()
        paintText.color = Color.RED
        paintText.textSize = 100f
    }

    //绘制 canvas 画布,所有画布上都需要用笔(Paint)绘制
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val rectF = RectF(100f, 100f, 600f, 600f)
//        canvas.drawRect(rectF, paint)
        //圆范围,起始角度(默认3点方向),绘制角度,
        canvas.drawArc(rectF, 270f, progress, false, paint)
        canvas.drawText(num.toString(), 320f, 380f, paintText)
    }

    fun start() {
        //kotlin中的new Thread
        runBlocking {
            val animator = ValueAnimator.ofFloat(0f, 360f)
            animator.addUpdateListener {
                progress = it.animatedValue as Float
                //重新绘制当前的View
                invalidate()
            }
            animator.duration = 5000
//            animator.interpolator = AccelerateDecelerateInterpolator()
            animator.interpolator = LinearInterpolator()
            animator.start()
        }

        runBlocking {
            val animatorText = ValueAnimator.ofInt(num, 0)
            animatorText.addUpdateListener {
                num = it.animatedValue as Int
                invalidate()
            }
            animatorText.interpolator = LinearInterpolator()
            animatorText.duration = num * 1000L
            animatorText.start()
        }
    }
}